<?php
/**
 * Created by PhpStorm.
 * User: lenovo
 * Date: 2018/5/24
 * Time: 18:50
 */

namespace app\index\controller;

use think\Controller;
use think\Db;
use think\Session;

/**
 * 请求代理服务器获取微信用户信息
 */
class Lovewauth extends Controller
{
    protected $appid,$appsecret;

    public function __construct()
    {
        $info = Db::name('option')->where([ 'option_name' => 'wx'])->field('option_value')->find();
        if($info['option_value']){
            $arr = json_decode($info['option_value'], true);
            $this->appid        = $arr['appid'];
            $this->appsecret    = $arr['appsecret'];
        }
    }

    /**
     * 微信授权
     */
    public function getRequest()
    {
        // 回调地址
        $redirecturl = urlencode($_SERVER['REQUEST_SCHEME'].'://'.$_SERVER['SERVER_NAME'].'/index/lovewauth/getInfo');

        // 微信接口地址
        $snsapi_userInfo_url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid='.$this->appid.'&redirect_uri='.$redirecturl.'&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect';

        // 请求接口
        header('Location:'.$snsapi_userInfo_url);
    }

    /**
     * 接收微信回调并处理数据
     */
    public function getInfo()
    {
        $code = $_GET['code'];
        if( isset($code) ){

            //1.通过code换取网页授权access_token
            $curl = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid='.$this->appid.'&secret='.$this->appsecret.'&code='.$code.'&grant_type=authorization_code';
            $content = file_get_contents($curl);
            $result = json_decode($content);

            //2.通过access_token和openid拉取用户信息
            $webAccess_token = $result->access_token;
            $openid = $result->openid;
            $userInfourl = 'https://api.weixin.qq.com/sns/userinfo?access_token='.$webAccess_token.'&openid='.$openid.'&lang=zh_CN ';

            // 3.获取信息
            $recontent = file_get_contents($userInfourl);

            // 4.用户信息
            $userInfo = json_decode($recontent,true);

            // 验证用户是否存在
            $u_info = Db::name('dd_activity_gk')
                ->where('openid',$userInfo['openid'])
                ->find();

            // 用户已存在
            if(!empty($u_info) && isset($u_info)){

                // 写入缓存
                Session::set('openid',$userInfo['openid']);
                Session::set('uid',$u_info['uid']);

                // 用户首次访问
            }else{
                $params['nickname']     = $userInfo['nickname'];        // 微信昵称
                $params['headimgurl']   = $userInfo['headimgurl'];      // 头像
                $params['openid']       = $userInfo['openid'];          // openid
                $params['create_time']  = time();                       // 注册时间

                $in_id = Db::name('dd_activity_gk')->insertGetId($params);


                Session::set('openid',$userInfo['openid']);
                Session::set('uid',$in_id);

            }
            // 跳转到首页
            header('Location:'.url('index/love.activity/index'));

        } else {

            // 重新获取用户信息
            header('Location:'.url('getRequest'));
        }
    }

    /**
     * 模拟登陆
     * @return [type] [description]
     */
    public function login()
    {
        Session::set('openid','oTJiusy8WdHVlalXpPSKhv1uZ3JI');
        Session::set('uid',1);

        $this->success('模拟登陆成功~',url('index/love.activity/index'));
    }


    /**
     * 重新登录
     */
    public  function loginOut()
    {
        Session::clear();

        $this->success('重新登录中...',url('index/index/index'));
    }

}